package tau.youtube;

import java.io.IOException;
import java.net.URL;

import com.google.gdata.client.Query;
import com.google.gdata.client.youtube.YouTubeQuery;
import com.google.gdata.client.youtube.YouTubeService;
import com.google.gdata.data.Category;
import com.google.gdata.data.youtube.VideoEntry;
import com.google.gdata.data.youtube.VideoFeed;
import com.google.gdata.data.youtube.YouTubeNamespace;
import com.google.gdata.util.ServiceException;

public class YouTubeAPI {

    public enum PlayerType {
	PC_PLAYER, MAC_PLAYER
    }

    private static final String APP_NAME = "db-project";
    private static final String DEVELOPER_ID = "AI39si4dqwnCC6P3C-qUY1R8EHhgJ1f9V5oTvu9CQ_W_r7asV7ER1Z221_guEguOXpyVvZxVzbs_tcdMrp4R72hGbBx3rH9NTQ";

    private YouTubeService service;

    public YouTubeAPI() {
	this.service = new YouTubeService(APP_NAME, DEVELOPER_ID);
    }

    public String GetVideoURL(String song_name, String artist_name,
	    PlayerType player_type) throws IOException, ServiceException {

	YouTubeQuery query = new YouTubeQuery(new URL(
		"http://gdata.youtube.com/feeds/api/videos"));

	// add artist_name keyword & "Music" category filters
	Query.CategoryFilter categoryFilter = new Query.CategoryFilter();
	categoryFilter.addCategory(new Category(
		YouTubeNamespace.CATEGORY_SCHEME, "Music"));
	categoryFilter.addCategory(new Category(
		YouTubeNamespace.KEYWORD_SCHEME, artist_name));
	query.addCategoryFilter(categoryFilter);

	// sort by relevance
	query.setOrderBy(YouTubeQuery.OrderBy.RELEVANCE);

	// search for the video and include restricted content in the search
	// results
	query.setFullTextQuery(song_name + " " + artist_name);
	query.setSafeSearch(YouTubeQuery.SafeSearch.NONE);

	// get the video feed
	VideoFeed videoFeed = service.query(query, VideoFeed.class);

	if (videoFeed.getEntries().size() == 0)
	    return null;

	// get the url
	VideoEntry videoEntry = videoFeed.getEntries().get(0);
	String videoID = videoEntry.getMediaGroup().getVideoId();
	String url = null;
	if (player_type == PlayerType.PC_PLAYER)
	    url = "http://www.youtube.com/v/" + videoID
		    + "?version=3&enablejsapi=1&playerapiid=player1";
	else if (player_type == PlayerType.MAC_PLAYER)
	    url = "http://www.youtube.com/embed/" + videoID;

	// return
	return url;
    }
}
